package person.drf.shop.product.jucTest;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

public class FetureDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //有返回值异步回调
        // 实际应用可能有也可能没有！也即回调成功与失败
        CompletableFuture<Integer> completableFuture =  CompletableFuture.supplyAsync(()->{
            int i = 1/0;
            return 200;
        });

        completableFuture.whenComplete((t,u)->{  //成功时
            System.out.println("t=>"+t);  //  t:正常返回结果
            System.out.println("u=>"+u);  //  u:错误信息

        }).exceptionally((e)->{  //失败时
            System.out.println(e.getMessage());  //可以获取错误的返回结果
            return 500;
        });



    }

    private static void voidDemo() throws InterruptedException, ExecutionException {
        //没有返回值的异步回调
        CompletableFuture<Void> completableFuture =  CompletableFuture.runAsync(()->{
            //假装延迟
            try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); }
            System.out.println(Thread.currentThread().getName()+"堵塞线程runAsync -> Void");
        });

        System.out.println(Thread.currentThread().getName()+"主线程1111");
        completableFuture.get();
    }
}
